/*
 * @Author: szx
 * @Date: 2021-12-29 13:04:14
 * @LastEditTime: 2021-12-29 13:20:15
 * @Description:
 * @FilePath: \leetcode\1900-1999\1995\1995.js
 */
/**
 * @param {number[]} nums
 * @return {number}
 */
var countQuadruplets = function (nums) {
    let n = nums.length;
    let ans = 0;
    const cnt = new Map();
    // 这个逆序反倒是关键的部分，这样子只有遍历一遍就行了
    for (let b = n - 3; b >= 1; --b) {
        for (let d = b + 2; d < n; ++d) {
            cnt.set(nums[d] - nums[b + 1], (cnt.get(nums[d] - nums[b + 1]) || 0) + 1);
        }
        for (let a = 0; a < b; ++a) {
            let sum = nums[a] + nums[b];
            if (cnt.has(sum)) {
                ans += cnt.get(sum);
            }
        }
    }
    return ans;
};
console.log(countQuadruplets([1, 2, 3, 6]));
